const statusLogic = require('../business-logic/status');
const spawn = require('child_process').spawn;


let runningCount = 0;

function getCheckTimeDelay() {
    let randomNum = Math.floor(Math.random() * 5) + 5;
    return (randomNum + 5 * 6) * 100;
}

async function chekcCrawler() {
    console.log('check crawler')
    let status = await statusLogic.query();
    if (status.crawlerStatus === 1) {
        runningCount++;
        if (runningCount >= 3) {
            runningCount = 0;
            restartCrawler();
            return;
        }
    } else {
        runningCount = 0;
    }
    setTimeout(chekcCrawler, getCheckTimeDelay());
}

chekcCrawler();

function restartCrawler() {
    console.log('restart crawler');
    spawn('pm2', [
        'restart',
        'news-monit-crawler'
    ]);
}

module.exports = {}